<template>
  <div class="service-list-container">
    <div class="page-header">
      <h2>宠物服务</h2>
      <p>为您的爱宠提供专业的服务</p>
    </div>

    <el-row :gutter="20">
      <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="service in services" :key="service.id">
        <el-card class="service-card" shadow="hover">
          <div class="service-image">
            <img :src="getImageUrl(service.imageUrl) || require('@/assets/default-service.jpg')" alt="服务图片">
          </div>
          <div class="service-card-header">
            <h3>{{ service.name || '未命名服务' }}</h3>
            <div class="service-category">{{ service.category || '未分类' }}</div>
          </div>
          <div class="service-card-body">
            <div class="service-description">{{ service.description || '暂无描述' }}</div>
            <div class="service-details">
              <div class="price">￥{{ service.price || '0' }}</div>
              <div class="duration">{{ service.duration || '0' }}分钟</div>
            </div>
          </div>
          <div class="service-card-footer">
            <el-button type="primary" @click="handleAppointment(service)" :disabled="!isLoggedIn">在线预约</el-button>
            <el-button type="text" @click="showServiceDetail(service.id)">查看详情</el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog
      title="预约服务"
      :visible.sync="dialogVisible"
      width="500px"
      @close="resetForm">
      <el-form :model="form" :rules="rules" ref="appointmentForm" label-width="100px">
        <el-form-item label="服务名称">
          <span>{{ currentService.name }}</span>
        </el-form-item>
        <el-form-item label="服务价格">
          <span>￥{{ currentService.price }}</span>
        </el-form-item>
        <el-form-item label="服务时长">
          <span>{{ currentService.duration }}分钟</span>
        </el-form-item>
        <el-form-item label="选择宠物" prop="petId">
          <el-select v-model="form.petId" placeholder="请选择宠物" style="width: 100%">
            <el-option
              v-for="pet in pets"
              :key="pet.id"
              :label="pet.name"
              :value="pet.id">
            </el-option>
          </el-select>
          <div v-if="!hasPets" class="no-pets-tip">
            您还没有添加宠物信息，请先 
            <router-link to="/main/pets/create">添加宠物</router-link>
          </div>
        </el-form-item>
        <el-form-item label="预约日期" prop="appointmentDate">
          <el-date-picker
            v-model="form.appointmentDate"
            type="date"
            placeholder="选择日期"
            :picker-options="datePickerOptions"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-time-select
            v-model="form.appointmentTime"
            :picker-options="{
              start: '09:00',
              step: '00:30',
              end: '18:00'
            }"
            placeholder="选择时间"
            style="width: 100%">
          </el-time-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注信息"
            :rows="3">
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAppointment" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getServiceList } from '@/api/service'
import { getMyPets } from '@/api/pet'
import { createAppointment } from '@/api/service'
import { mapState } from 'vuex'

export default {
  name: 'ServiceList',
  data() {
    return {
      services: [],
      pets: [],
      loading: false,
      dialogVisible: false,
      currentService: {},
      form: {
        petId: '',
        appointmentDate: '',
        appointmentTime: '',
        remark: ''
      },
      rules: {
        petId: [
          { required: true, message: '请选择宠物', trigger: 'change' }
        ],
        appointmentDate: [
          { required: true, message: '请选择预约日期', trigger: 'change' }
        ],
        appointmentTime: [
          { required: true, message: '请选择预约时间', trigger: 'change' }
        ]
      },
      datePickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
        }
      }
    }
  },
  computed: {
    ...mapState('user', ['userInfo']),
    isLoggedIn() {
      return !!this.userInfo;
    },
    hasPets() {
      return this.pets.length > 0;
    }
  },
  created() {
    this.fetchServices();
    if (this.isLoggedIn) {
      this.fetchMyPets();
    }
  },
  methods: {
    getImageUrl(path) {
      if (!path) return '';
      
      // 如果已经是完整的URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径格式正确
      const cleanPath = path.startsWith('/') ? path : `/${path}`;
      
      // 返回完整的URL
      return `http://localhost:8080${cleanPath}`;
    },
    
    async fetchServices() {
      try {
        this.loading = true;
        const response = await getServiceList();
        if (response.code === 200) {
          // 处理不同的数据结构，优先使用list字段
          if (response.data && response.data.list) {
            this.services = response.data.list;
          } else if (Array.isArray(response.data)) {
            this.services = response.data;
          } else {
            this.services = [];
            console.error('未知的服务数据格式:', response.data);
          }
          console.log('获取到的服务数据:', this.services);
        } else {
          this.$message.error(response.message || '获取服务列表失败');
        }
      } catch (error) {
        console.error('获取服务列表失败:', error);
        this.$message.error('获取服务列表失败');
      } finally {
        this.loading = false;
      }
    },
    
    async fetchMyPets() {
      try {
        const response = await getMyPets();
        if (response.code === 200) {
          this.pets = response.data;
        } else {
          this.$message.error(response.message || '获取宠物列表失败');
        }
      } catch (error) {
        console.error('获取宠物列表失败:', error);
        this.$message.error('获取宠物列表失败');
      }
    },
    
    handleAppointment(service) {
      if (!this.isLoggedIn) {
        this.$message.warning('请先登录');
        this.$router.push('/login');
        return;
      }
      
      this.currentService = service;
      this.dialogVisible = true;
      
      console.log('预约服务:', this.currentService);
      
      // 如果没有宠物，提示用户先添加宠物
      if (!this.hasPets) {
        this.fetchMyPets();
      }
    },
    
    showServiceDetail(serviceId) {
      this.$router.push(`/main/services/${serviceId}`);
    },
    
    resetForm() {
      if (this.$refs.appointmentForm) {
        this.$refs.appointmentForm.resetFields();
      }
      this.form = {
        petId: '',
        appointmentDate: '',
        appointmentTime: '',
        remark: ''
      };
    },
    
    submitAppointment() {
      this.$refs.appointmentForm.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            
            // 组合日期和时间
            const date = this.form.appointmentDate;
            const timeStr = this.form.appointmentTime;
            if (!date || !timeStr) {
              this.$message.warning('请选择预约日期和时间');
              return;
            }
            
            const [hours, minutes] = timeStr.split(':').map(Number);
            date.setHours(hours, minutes, 0, 0);
            
            const appointmentData = {
              serviceId: this.currentService.id,
              petId: this.form.petId,
              appointmentTime: date.toISOString(),
              remark: this.form.remark
            };
            
            const response = await createAppointment(appointmentData);
            
            if (response.code === 200) {
              this.$message.success('预约成功');
              this.dialogVisible = false;
              this.$router.push('/main/my-appointments');
            } else {
              this.$message.error(response.message || '预约失败');
            }
          } catch (error) {
            console.error('预约失败:', error);
            this.$message.error('预约失败，请稍后再试');
          } finally {
            this.loading = false;
          }
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.service-list-container {
  padding: 20px;
  
  .page-header {
    margin-bottom: 30px;
    text-align: center;
    
    h2 {
      font-size: 28px;
      color: #333;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 16px;
      color: #666;
    }
  }
  
  .service-card {
    height: 100%;
    margin-bottom: 20px;
    transition: all 0.3s;
    
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }
    
    .service-image {
      height: 150px;
      overflow: hidden;
      border-bottom: 1px solid #eee;
      margin-bottom: 10px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .service-card-header {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
      margin-bottom: 10px;
      
      h3 {
        margin: 0;
        font-size: 18px;
        color: #333;
      }
      
      .service-category {
        margin-top: 5px;
        font-size: 14px;
        color: #666;
        background: #f5f7fa;
        display: inline-block;
        padding: 2px 8px;
        border-radius: 4px;
      }
    }
    
    .service-card-body {
      .service-description {
        font-size: 14px;
        color: #666;
        margin-bottom: 15px;
        height: 60px;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
      
      .service-details {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .price {
          font-size: 18px;
          color: #f56c6c;
          font-weight: bold;
        }
        
        .duration {
          font-size: 14px;
          color: #666;
        }
      }
    }
    
    .service-card-footer {
      margin-top: 15px;
      display: flex;
      justify-content: space-between;
    }
  }
  
  .no-pets-tip {
    margin-top: 5px;
    font-size: 12px;
    color: #e6a23c;
  }
}
</style> 